package org.subside.rabbitmq.PublishAndSubscribe;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;
import org.subside.rabbitmq.config.ConnectionUtil;

import java.io.IOException;

public class ConsumerSubAndPub1 {
    private static final String EXCHANGE_NAME = "SubAndPubExchange1";
    private static final String ROUTING_KEY = "";
 
    public static void main(String[] args) throws Exception {
        Connection connection =  ConnectionUtil.getConnection();
        Channel channel = null;
        try {
            channel = connection.createChannel();
            //声明交换器 并指定类型为fanout（广播）  发布订阅模式，只要订阅了，就会收到消息
            channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
            String queue = channel.queueDeclare().getQueue();
            channel.queueBind(queue, EXCHANGE_NAME, ROUTING_KEY);
            System.out.println("消费者1监听"+queue+"中。。。");
            DeliverCallback callback = new DeliverCallback() {
                @Override
                public void handle(String consumerTag, Delivery message) throws IOException {
                    String msg = new String(message.getBody(), "UTF-8");
                    System.out.println(msg);
                }
            };
            channel.basicConsume(queue, true, callback, consumerTag->{});
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}